#coding=utf8
import flask
from flask import *
import requests
import time
import hashlib
import logging  
import os
import sys
from wechat_sdk import WechatBasic


console = logging.StreamHandler()
console.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s')
console.setFormatter(formatter)

log_file = logging.FileHandler('log.txt')
log_file.setFormatter(formatter)
log_file.setLevel(logging.DEBUG)

log = logging.getLogger('weixin-test')
log.setLevel(logging.DEBUG)
log.addHandler(console)
log.addHandler(log_file)


try:
    import xml.etree.cElementTree as ET
except ImportError:
    import xml.etree.ElementTree as ET

#微信
APPID = 'wx31991f813e69468c'
APPSECRET = 'ffc85796e6e56d8bd8bda7c0c07fccbc'
APPTOKEN = '5ed12a46dfddeac054837591cdec7836'

app = Flask(__name__)   
wechat = WechatBasic(token=APPTOKEN)


@app.route('/weixin', methods=['POST', 'GET'])
def weixinroute():
    parm = flask.request.args.to_dict()
    if len(parm) == 0: return "no parm"
    ar = "".join(sorted([parm['nonce'], parm['timestamp'], APPTOKEN]))
    valid = hashlib.sha1(ar).hexdigest() == parm['signature']
    if flask.request.method == 'GET':
        if valid:
            return parm['echostr']
        return ""
    elif valid == False:
        return ""
    return parseWeixinMsg(flask.request.data)

def parseWeixinMsg(data):
    log.debug('parse %s',data)
    wechat.parse_data(data)
    message = wechat.get_message()
    response = None
    if message.type == 'text':
        response = wechat.response_text(u'请回复语音查看语音识别结果')
        r_text = parseText(message.content)
        response = wechat.response_text(r_text)
    elif message.type == 'image':
        response = wechat.response_text(u'图片')
    elif message.type == 'voice':
        if message.recognition and len(message.recognition)>0:
            r_text = u'voice:'+message.recognition
            r_text += parseText(message.recognition)
            response = wechat.response_text(r_text)
        else :
            response = wechat.response_text(u'语音识别没有结果')

    else:
        response = wechat.response_text(u'uknow')
    return response

class Token():
    '''
    获取并缓存access_token
    '''
    def __init__(self):
        self.refresh_token()
        self.expires = time.time()
    def refresh_token(self):
        URL_GET_TOKEN = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s"%(APPID,APPSECRET)
        r = requests.get(URL_GET_TOKEN).text
        self.token = json.loads(r)['access_token']

    def get_token(self):
        if time.time()-self.expires > 3600:
            self.refresh_token()
            self.expires = time.time()
        return self.token


def parseText(text):
    from jinja2 import Template
    # from snownlp import SnowNLP
    from  theme_analysis import get_theme

    # snownlp = SnowNLP(text)

    # keyword = snownlp.keywords(3)   # [u'语言', u'自然', u'计算机']

    # summary = snownlp.summary(3)    # [u'因而它是计算机科学的一部分',
    theme = get_theme(text)
    '''关键字：{{keyword|join('|')}}
    文本摘要：{{summary|join('|')}}
    '''
    template = Template(u'''
原始文本:{{text}}
主题分析:{{theme|join('|')}}
''')
    return template.render(locals())
    
@app.route('/')
def index():
    return 'weixin-voice-test run'

if __name__=='__main__':
    token_cache = Token()
    app.run(host='0.0.0.0',debug=True)

    log.debug('Exit----------')

import unittest
class Test(unittest.TestCase):
    def test_1(self):
        with app.test_request_context('/weixin'):

            data = '''<xml><ToUserName><![CDATA[gh_5cebe2cf8ce4]]></ToUserName>
    <FromUserName><![CDATA[ovu1bs7gc0XGigISZFjH3SUE7_Hs]]></FromUserName>
    <CreateTime>1419237602</CreateTime>
    <MsgType><![CDATA[voice]]></MsgType>
    <MediaId><![CDATA[dPEEQiF2EP3jfCGsQc3FQbZVXVa2MO9YWqABHDIBgLzlROBExisLI1X50IPik2i9]]></MediaId>
    <Format><![CDATA[amr]]></Format>
    <MsgId>6095579085843464192</MsgId>
    <Recognition><![CDATA[测试]]></Recognition>
    </xml>'''
            print(parseWeixinMsg(data))

    def test_2(self):
        print(parseText(u'宫保鸡丁的做法'))
        print(parseText(u'公众平台开发接口提供与用户进行消息交互、自定义菜单交互的能力。对于成功接入公众平台开发接口的公众账号，当用户发消息给公众号，微信公众平台服务器会使用http请求对接入的网址进行消息推送，第三方服务器可通过响应包回复特定结构，从而达到回复消息的目的。'))


